<template>
  <div class="app-container">
    <el-row>
      <el-form :model="queryParams"  ref="queryForm" :inline="true" v-show="showSearch">
        <el-form-item label="姓名">
          <el-input v-model="queryParams.studentName" placeholder="请输入姓名" clearable />
        </el-form-item>


        <el-form-item label="注册号">
          <el-input v-model="queryParams.regCode" placeholder="请输入注册号" clearable />
        </el-form-item>


        <el-form-item label="所在院部">
          <!-- <el-cascader v-model="queryParams.deptId" :options="deptOptions"
            :props="{ value: 'id', currentLabels: 'label', checkStrictly: true }" @change="handleChange"
            @keyup.enter.native="search"></el-cascader> -->
            <el-select v-model="queryParams.deptId" placeholder="请选择" clearable class="elSelect" @change="handleChange"  style="width: 100%">
              <el-option v-for="item in deptOptions" :key="item.deptId" :label="item.deptName"
                :value="item.deptId"></el-option>
            </el-select>
        </el-form-item>

        <el-form-item label="所选专业">
          <el-select v-model="queryParams.specialityId" clearable placeholder="请选择" @keyup.enter.native="search">
            <el-option v-for="item in profession" :key="item.VALUE" :label="item.TITILE" :value="item.VALUE"></el-option>
          </el-select>
        </el-form-item>


        <el-form-item>
          <div style="float:right;">
            <el-button type="primary" icon="el-icon-search" @click="handleQuery" size="mini">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </div>
        </el-form-item>

      </el-form>
    </el-row>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['psy:blacklist:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['psy:blacklist:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['psy:blacklist:remove']">删除</el-button>
      </el-col>
      <right-toolbar @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="blackList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="注册号" align="center" prop="regCode" />
      <el-table-column label="学生姓名" align="center" prop="studentName" :show-overflow-tooltip="true" />
      <el-table-column label="院系专业" align="center" prop="dm" :show-overflow-tooltip="true">
      </el-table-column>
      <el-table-column label="黑名单状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.psy_bl_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="黑名单时效性" align="center" prop="blStartEndDateStr"></el-table-column>
      <el-table-column label="添加人" align="center"  prop="createBy"></el-table-column>
      <el-table-column label="添加时间" align="center"  prop="createTime"></el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open"  @close="cancel" width="500px" append-to-body  destroy-on-close>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
      <el-form-item label="学生注册号" prop="studentName">
         <el-input v-model="regCode" placeholder="请输入学生注册号" />
          {{ form.studentName }} {{ form.dm }}
        </el-form-item>
      <el-form-item label="黑名单时效" prop="blStartTime">
          <el-date-picker v-model="dateRanges" type="daterange" align="right" unlink-panels range-separator="至"
            start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions" value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
  
<script>
import { deptTreeSelect } from "@/api/system/user";
import { getSpecialityByDeptId } from "@/api/information/unitMajor";
import { blacklistList, getStudentDpm,addBlacklist,updataBlacklist,delBlacklist,getBlacklist } from "@/api/psychological/basic"
import {
  collegeSelect
} from "@/api/information/studentInfor"
export default {
  name: "Dict",
  dicts: ['psy_bl_status'],
  data() {
    return {
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      // 遮罩层
      loading: false,
      showSearch: true,
      // 选中数组
      ids: [],
      names: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      // 总条数
      total: 0,
      // 字典表格数据
      blackList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRanges: [],

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        specialityId: undefined,
        dictName: undefined,
        dictType: undefined,
        status: undefined
      },
      // 表单参数
      form: {
        studentName:'',
        dm: '',
      },
      rules: {
        studentName: [
          { required: true, message: "请输入注册号", trigger: "blur" }
        ],
        blStartTime: [
          { required: true, message: "请选择时间", trigger: "change" }
        ],
      },
      deptOptions: [],
      profession: [],
      regCode: '', // 注册号 
      timeout: '',
      
    };
  },
  watch: {
    regCode(curVal, oldVal) {
      // 实现input连续输入，只发一次请求
      clearTimeout(this.timeout)
      this.timeout = setTimeout(() => {
        this.handleChangeName(curVal)
      }, 500)
    }
  },
  created() {
    this.getList();
    this.department();
  },
  methods: {
    /** 查询字典类型列表 */
    getList() {
      blacklistList(this.queryParams).then(response => {
        this.blackList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 获取部门信息
    async department() {
      await collegeSelect().then(res => {
        this.deptOptions = res.data;
      });
    },
    handleChangeName(value) {
      console.log(value,'注册号')
      if (value === '') {
        return false;
      }else {
        getStudentDpm({regCode:value}).then(res => {
          this.form.studentName = res.data.STUDENTNAME
          this.form.dm = res.data.DPM
          this.form.studentId =  res.data.STUDENT_ID
        })
      }
      console.log(value)
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.form = {}
      this.dateRanges = []
      this.regCode = ''
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {};
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = 10;
      this.handleQuery();
    },
    // 下拉树选择
    handleChange(value) {
      this.form.deptId = value
      this.queryParams.deptId = value
      this.form.specialityId = "";
      this.getSpeciality();
      // if (typeof value == "object") {
      //   this.form.deptId = value[value.length - 1];
      //   this.queryParams.deptId = value[value.length - 1];
      //   this.getSpeciality();
      // } else if (typeof value == "number") {
      //   this.form.deptId = value;
      //   this.getSpeciality();
      // } else if (value == undefined) {
      //   this.form.specialityId = "";
      // }
    },
    getSpeciality() {
      if (this.form.deptId) {
        getSpecialityByDeptId({ deptId: this.form.deptId }).then(res => {
          if (res.code == "200") {
            this.profession = res.data;
          } else {
            console.log("123");
            this.profession = [];
          }
        });
      } else {
        this.profession = [];
      }
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.open = true;
      this.title = "添加";
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.pbId)
      this.names = selection.map(item => item.studentName);
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.dateRanges = []
      this.form.pbId = row.pbId
      this.open = true
      this.regCode = row.regCode
      this.dateRanges.push(row.blStartTime,row.blEndTime)
      // console.log(this.dateRanges,'dfsjf')
      // getBlacklist(row.pbId).then(res => {
      //   console.log(res)
      //   this.open = true
      // })
    },
    /** 提交按钮 */
    submitForm: function () {
      console.log(this.dateRanges,this.regCode)
      if(this.dateRanges == [] || this.regCode == '') {
        this.$modal.msgError("请填写注册号或选择时间");
      }else {
        if(this.dateRanges){
        console.log(this.dateRanges)
        this.form.blStartTime = this.dateRanges[0]
      this.form.blEndTime = this.dateRanges[1]
      }
     
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.pbId != undefined) {
            updataBlacklist(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.regCode = ''
              this.dateRanges = []
              this.form = {}
            });
          } else {
            addBlacklist(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.regCode = ''
              this.dateRanges = []
              this.form = {}
            });
          }
        }
      });
      }
      
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const cebIds = row.pbId || this.ids;
      this.names = row.studentName || this.names;
      this.$modal
        .confirm('是否确认删除黑名单学生姓名为："' + this.names + '"的数据项？')
        .then(function () {
          return delBlacklist(cebIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    }
  }
};
</script>